<?php
/*
 * Copyright notice
 * 
 * (c) 2009 MH-Dev.de, Martin Hesse <info@mh-dev.de>
 * 
 * This script is part of the MH-Dev.-Board project. The MH-Dev.-Board 
 * is free software; you can redistribute it and/or modify it under the 
 * terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, 
 * or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty 
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU 
 * General Public License along with this program; if not, 
 * see http://www.gnu.org/licenses/.
 */


/**
 * ProfileController
 *
 * @author	Martin Hesse <info@mh-dev.de>
 * @package	MH-Dev.-Board
 */
class ProfileController extends Zend_Controller_Action
{
	private $registry; // registry
	private $auth; // user-values
	private $settings; // settings
	private $translate; // translation
	
	public function init()
	{		
		// registry
		$this->registry = Zend_Registry::getInstance();
		
		// auth
		$auth = Zend_Auth::getInstance();
    	$this->view->auth = $auth->hasIdentity();
    	
    	if($auth->hasIdentity())
    	{
    		$this->view->auth_role 			= $auth->getIdentity()->role;
    		$this->view->username 			= $auth->getIdentity()->username;
    		$this->view->auth_uid			= $auth->getIdentity()->uid;
    		$this->view->unread_messages	= $auth->getIdentity()->count_unread_messages;
    	}
    	else
    	{
    		$this->view->username 	= $this->registry->get('lang')->_('guest');
    	}

    	$this->auth = $auth;
    	
    	// settings
    	$this->settings 			= $this->registry->get('settings');
		
    	// lang
    	$this->translate			= $this->registry->get('lang');
		$this->view->translate		= $this->translate;
		
		// flash messenger
		$this->view->flashMessenger	= $this->_helper->FlashMessenger;
		
		// settings: allow upload
		$this->view->allow_upload	= $this->settings['avatar_upload'];
		
		// include jquery
		$baseurl = new MHDEV_View_Helper_BaseUrl();
		$this->view->headScript()->appendFile($baseurl->BaseUrl() . '/static/css/default/jquery.css');
		$this->view->headScript()->appendFile($baseurl->BaseUrl() . '/static/js/jquery-1.3.2.min.js');
		$this->view->headScript()->appendFile($baseurl->BaseUrl() . '/static/js/jquery-ui-1.7.2.custom.min.js');
	}
	
	/*
	 * Get the user profile
	 * 
	 * @param null
	 * 
	 * @return void
	 */
	public function indexAction()
	{
		// param
		$uid 		= $this->_request->getParam('uid', 0);
		
		// db
		$user 		= new User();
		$posts		= new Posts();
		$guestbook	= new UserGuestbook();
		$buddies	= new Buddies();
		
		// query
		$query		= $user->find($uid);
		
		// update profile hits +1
		if(!$this->auth->hasIdentity()) 
		{ 
			$user->update(array('count_hits' => new Zend_Db_Expr('count_hits+1')), 'uid=' . $uid); 
		}
		elseif($uid != $this->auth->getIdentity()->uid && $query->count() > 0)
		{
			$user->update(array('count_hits' => new Zend_Db_Expr('count_hits+1')), 'uid=' . $uid); 
		}
		
		// buddy-check
		if($this->auth->hasIdentity())
		{
			if($uid != $this->auth->getIdentity()->uid)
			{
				$checkBuddy	= $buddies->fetchAll('`user_uid`=' . $this->auth->getIdentity()->uid .' AND `buddy_uid` = ' . intval($uid));
				
				if($checkBuddy->count() == 0)
				{
					$this->view->checkBuddy = true;
				}
			}
		}
		
		// get buddies
		$getBuddies	= $buddies->fetchAll('`accepted` = 1 AND `user_uid`=' . $uid);
		
		// get last 10 posts
		$getPosts 	= $posts->select()->setIntegrityCheck(false);
		$getPosts->from(
				array('p' => 'posts')
			)
			->join(
				array('t' => 'threads'), 'p.thread_uid = t.uid', array('title', 'uid', 'last_reply_date')
			)
			->join(
				array ('b' => 'boards'), 't.board_uid = b.uid', array('title AS bTitle')
			)
			->where('p.user_uid = ?', intval($uid))
			->where('t.is_public = ?', 1)
			->where('t.is_deleted = ?', 0)
			->order('p.create_date DESC')
			->limit(10);
		
		$queryPosts	= $posts->fetchAll($getPosts);
		
		// get sum of gb entries
		$gbQuery	= $guestbook->fetchAll('is_deleted = 0 AND guestbook_uid =' . intval($uid));
		
		// view
		$this->view->count			= $query->count();
		$this->view->results		= $query->toArray();
		$this->view->post_count		= $queryPosts->count();
		$this->view->post_results	= $queryPosts->toArray();
		$this->view->gb_count		= $gbQuery->count();
		$this->view->buddy_count	= $getBuddies->count();
		$this->view->buddy_res		= $getBuddies->toArray();
	}
	
	
	
	/*
	 * Allows a user to edit his profile
	 * 
	 * @param null
	 * 
	 * @return void
	 */
	public function editAction()
	{
		// param
		$user_uid	= $this->auth->getIdentity()->uid;
		
		// form
		$form 		= new ProfileForm();
		
		// db
		$user		= new User();
		$layouts	= new Layouts();
		$guestbook	= new UserGuestbook();
		
		// query
		$query		= $user->find($user_uid);
		$getLayouts	= $layouts->fetchAll('is_public = 1');
		
		if($query->count() > 0)
		{
			$res		= $query->toArray();
			$formData 	= $this->_request->getPost();

			
			if($this->_request->isPost() && $form->isValid($formData))
			{
				if($res[0]['uid'] == $user_uid)
				{
					$passwd = $form->getValue('password');
					$form->removeElement('password');
					$form->removeElement('submit');
					$user->update($form->getValues(), 'uid=' . $user_uid);
					
					if(strlen($passwd) > 0)
					{
						$user->update(array('password' => md5($passwd)), 'uid=' . $user_uid);
					}
					
					$this->_helper->FlashMessenger($this->translate->_('flash_profile_update'));
					$this->_redirect('/profile/edit.html');
				}
			}
			else
			{
				// fill layout-field
				$getLayout	= $form->getElement('layout');
				
				foreach($getLayouts->toArray() AS $layout)
				{
					$getLayout->addMultiOption($layout['key'], $layout['title']);
				}
			
				$form->populate($res[0]);
			}
		}
		else
		{
			$this->_redirect('/');
		}
		
		// get sum of gb entries
		$gbQuery	= $guestbook->fetchAll('is_deleted = 0 AND guestbook_uid =' . $user_uid);

		// view
		$this->view->form 		= $form;
		$this->view->gb_count	= $gbQuery->count();
	}
	
	
	
	/*
	 * Allows a user to change his avatar
	 * 
	 * @param null
	 * 
	 * @return null
	 */
	public function avatarAction()
	{
		// vars
		$uid			= $this->auth->getIdentity()->uid;
		$formData		= $this->_request->getPost();
		$error			= FALSE;

		// db
		$guestbook		= new UserGuestbook();
		$user			= new User();
		
		// form
		$form			= new AvatarForm();
		$gForm			= new GravatarForm();
		
		// helper
		$getUserAvatar		= new MHDEV_View_Helper_GetUserAvatar();
		$getAvatarSource	= new MHDEV_View_Helper_GetAvatarSource();
		
		// res
		$getUser	= $user->find($uid);
		
		if($getUser->count() > 0)
		{
			$userArr	= $getUser->toArray();
			$gForm->populate($userArr[0]);
			
			if(strlen($userArr[0]['gravatar_mail']) == 0)
			{
				$gForm->getElement('gravatar_mail')->setValue($userArr[0]['mail']);
			}
		}
		
		// check if enabled
		if($this->_request->isPost())
		{
			// get post and do upload
			if ($this->settings['avatar_upload'] == 1 && $form->isValid($formData)) 
			{
				if($formData['is_deleted'] == 1)
				{
					if($getUserAvatar->GetUserAvatar($uid, TRUE))
					{
						@unlink($getAvatarSource->GetAvatarSource($uid));
						$this->_redirect('/profile_' . $uid . '.html');
					}
				}
				
				$upload	= new Zend_File_Transfer_Adapter_Http();
				$upload->setDestination('upload/temp');
				
				$imgArr 		= getimagesize($_FILES['upload']['tmp_name']);
				$image_width 	= $imgArr[0];
				$image_height 	= $imgArr[1];
				$imgSize		= round((filesize($_FILES['upload']['tmp_name'])/1024));
				
				if($this->settings['avatar_width'] >= $image_width && $this->settings['avatar_height'] >= $image_height && $this->settings['avatar_size'] >= $imgSize)
				{
					$getFileExt = explode('.', $upload->getFileName('upload'));
					
					$GetUserAvatar = new MHDEV_View_Helper_GetUserAvatar();
			
					if($getUserAvatar->GetUserAvatar($uid, TRUE))
					{
						@unlink($getAvatarSource->GetAvatarSource($uid));
					}
						
					if($upload->receive())
					{
						$newFileName = 'upload/avatar/' . $uid . '.' . strtolower($getFileExt[1]);
			        	@rename($upload->getFileName('upload'), $newFileName);
			        	@chmod($newFileName,0777);
			        	$this->_helper->FlashMessenger($this->translate->_('flash_profile_avatar'));
					}
					else
					{
						$error = $this->translate->_('IMAGE_UPLOAD_ERROR');
					}
				}
				else
				{
					$error = $this->translate->_('IMAGE_WIDTH_OR_HEIGHT');
				}
				
				if(!$error)
				{
					$this->_redirect('/profile_' . $uid . '.html');
				}
			}
			elseif($gForm->isValid($formData))
			{
				$gForm->removeElement('submit');
				$user->update($gForm->getValues(), 'uid=' . $uid);
				$this->_helper->FlashMessenger($this->translate->_('flash_profile_gravatar'));
				$this->_redirect('/profile/avatar.html');
			}
		}
		
		// get sum of gb entries
		$gbQuery	= $guestbook->fetchAll('is_deleted = 0 AND guestbook_uid =' . $uid);
	
		// view
		$this->view->error		= $error;
		$this->view->form		= $form;
		$this->view->notice 	= MHDEV_Sprintf($this->translate->_('profile_avatar_notice'), array(
			'%size'		=> $this->settings['avatar_size'],
			'%width'	=> $this->settings['avatar_width'],
			'%height'	=> $this->settings['avatar_height'],
		));
		$this->view->gb_count	= $gbQuery->count();
		
		$this->view->gForm		= $gForm;
	}


	
	/*
	 * List entries from a user guestbook
	 * 
	 * @param null
	 * 
	 * @return void
	 */
	public function guestbookAction()
	{
		// bbcode-editor
		$this->initEditor();
		
		// vars
		$count		= 10;
		$page		= $this->_request->getParam('page', 0);
		$uid		= $this->_request->getParam('uid', 0);
		
		// db
		$db			= new UserGuestbook();
		
		// fetch
		$fetch		= $db->fetchAll('is_deleted = 0 AND guestbook_uid = ' . $uid, 'date DESC', $count);
		
		// paginator
		$paginator	= Zend_Paginator::factory($fetch->toArray());
        $paginator->setItemCountPerPage($count);
        $paginator->setCurrentPageNumber($page);
        
        if($this->_request->isPost() && $this->auth->hasIdentity())
        {
        	$this->addGuestbookEntry($this->_request->getPost(), $uid);
        }
        
        // get sum of gb entries
		$gbQuery	= $db->fetchAll('is_deleted = 0 AND guestbook_uid =' . $uid);
		
        // view
        $this->view->count		= $fetch->count();
        $this->view->results	= $paginator;
        $this->view->uid		= $uid;
        $this->view->gb_count	= $gbQuery->count();
	}
	
	
	
	/*
	 * Handle Post-Data from a new guestbook entry in a profile
	 * 
	 * @param array $post-data
	 * @param int uid of the user
	 * 
	 * @return boolean valid
	 */
	public function addGuestbookEntry($postData, $uid)
	{
		// db
		$guestbook	= new UserGuestbook();
		
		// form
		$form		= new UserGuestbookForm();

		if($form->isValid($postData))
		{
			$newEntryArray	= array(
				'user_uid'		=> $this->auth->getIdentity()->uid,
				'guestbook_uid'	=> $uid,
				'text'			=> $postData['text'],
				'date'			=> new Zend_Db_Expr('NOW()')
			);
			
			if($guestbook->insert($newEntryArray))
			{
				$this->_helper->FlashMessenger($this->translate->_('flash_profile_gb_new'));
				$this->_redirect('/profile/guestbook_' . $uid . '.html');
			}
			else
			{
				return false;
			}
		}
		else
		{
			return false;
		}
	}
	
	
	
	/*
	 * Delete a guestbook entry
	 * 
	 * @param null
	 * 
	 * @return void
	 */
	public function deleteguestbookentryAction()
	{
		// disable layout
		Zend_Layout::getMvcInstance()->disableLayout();
		
		// post
		$postData	= $this->_request->getPost();
		
		// db
		$guestbook	= new UserGuestbook();
		
		if($postData['uid'] > 0)
		{
			// query
			$getGB		= $guestbook->find((int)$postData['uid']);
			
			if($getGB->count() > 0)
			{
				$resGB	= $getGB->toArray();
				
				if($resGB[0]['guestbook_uid'] == $postData['uid'] OR $this->auth->getIdentity()->role == 'admin')
				{
					// helper
					$author	= new MHDEV_View_Helper_GetAuthor();
					
					// log
					$this->registry->get('log')->info('[USER Profile] Guestbook-Entry from ' . $author->GetAuthor($postData['uid']) . ' was deleted by User/Admin: ' . $author->GetAuthor($this->auth->getIdentity()->uid));
					
					// update gb entry
					$guestbook->update(array(
						'is_deleted'	=> 1
					), 'uid=' . (int)$postData['uid']);
				}
			}
		}
	}
	
	
	
	/*
	 * Add a buddy
	 * 
	 * @param null
	 * 
	 * @return void
	 */
	public function addbuddyAction()
	{
		// params
		$buddy_uid	= (int)$this->_request->getParam('uid', 0);
		$user_uid	= (int)$this->auth->getIdentity()->uid;
		
		// helper
		$pm			= new MHDEV_View_Helper_SendMessage();
		$author		= new MHDEV_View_Helper_GetAuthor();
		$url		= new Zend_View_Helper_Url();
		
		// db
		$buddies	= new Buddies();
		
		// query
		$check		= $buddies->fetchAll('`user_uid` = ' . $user_uid . ' AND `buddy_uid` =' . $buddy_uid);
		
		if($buddy_uid != $user_uid)
		{
			if($check->count() == 0)
			{
				$buddies->insert(array(
					'user_uid'	=> $user_uid,
					'buddy_uid'	=> $buddy_uid,
					'date'		=> new Zend_Db_Expr('NOW()')
				));
				
				// notify user
				$pm->SendMessage(
					$buddy_uid, 
					$this->translate->_('profile_pm_frequest_title'), 
					MHDEV_Sprintf($this->translate->_('profile_pm_frequest'), array(
			    		'%username'		=> $author->GetAuthor($user_uid),
			    		'%user_profile'	=> $url->url(
							array(
								'controller'	=> 'profile',
								'action'		=> 'index',
								'uid'			=> $user_uid
							), 
							'profile', 
							true
						),
						'%link_accept'	=> $url->url(
							array(
								'controller'	=> 'profile',
								'action'		=> 'setbuddy',
								'uid'			=> $user_uid,
								'mode'			=> 'accept'
							), 
							'buddy_mode', 
							true
						),
						'%link_deny'	=> $url->url(
							array(
								'controller'	=> 'profile',
								'action'		=> 'setbuddy',
								'uid'			=> $user_uid,
								'mode'			=> 'denied'
							), 
							'buddy_mode', 
							true
						)
		    		)
		    	));
				
				$this->_helper->FlashMessenger($this->translate->_('flash_profile_buddy1'));
			}
			else
			{
				$this->_helper->FlashMessenger($this->translate->_('flash_profile_buddy2'));
			}
		}
		else
		{
			$this->_helper->FlashMessenger($this->translate->_('flash_profile_buddy3'));
		}
		
		$this->_redirect('/profile_' . $buddy_uid . '.html');
	}
	
	
	
	/*
	 * Change the buddy-status
	 * 
	 * @param null
	 * 
	 * @return void
	 */
	public function setbuddyAction()
	{
		// params
		$mode		= $this->_request->getParam('mode', false);
		$buddy_uid	= (int)$this->_request->getParam('uid', 0);
		$user_uid	= $this->auth->getIdentity()->uid;
		
		// helper
		$pm			= new MHDEV_View_Helper_SendMessage();
		$author		= new MHDEV_View_Helper_GetAuthor();
		$url		= new Zend_View_Helper_Url();
		
		// db
		$buddies	= new Buddies();
		
		// check if valid
		$check		= $buddies->fetchAll('`user_uid` = ' . $buddy_uid . ' AND `buddy_uid`=' . $user_uid);

		if($check->count() > 0)
		{
			if($mode == 'accept')
			{
				$buddies->update(array(
					'accepted'	=> 1
				), '`user_uid` = ' . $buddy_uid . ' AND `buddy_uid`=' . $user_uid);
				
				$buddies->insert(array(
					'accepted'	=> 1,
					'user_uid'	=> $user_uid,
					'buddy_uid'	=> $buddy_uid,
					'date'		=> new Zend_Db_Expr('NOW()')
				));
				
				$pm->SendMessage(
					$buddy_uid, 
					MHDEV_Sprintf($this->translate->_('buddy_accepted_title'), array(
						'%username' => $author->GetAuthor($user_uid)
					)),
					$this->translate->_('buddy_accepted')
				);
				
				$this->_helper->FlashMessenger($this->translate->_('flash_buddy_accepted'));
			}
			elseif($mode == 'denied')
			{
				$buddies->delete('`user_uid` = ' . $buddy_uid . ' AND `buddy_uid`=' . $user_uid);

				$pm->SendMessage(
					$buddy_uid, 
					MHDEV_Sprintf($this->translate->_('buddy_denied_title'), array(
						'%username' => $author->GetAuthor($user_uid)
					)),
					$this->translate->_('buddy_denied')
				);
				
				$this->_helper->FlashMessenger($this->translate->_('flash_buddy_denied'));
			}
			elseif($mode == 'delete')
			{
				$buddies->delete('`user_uid` = ' . $buddy_uid . ' AND `buddy_uid`=' . $user_uid);
				$buddies->delete('`user_uid` = ' . $user_uid . ' AND `buddy_uid`=' . $buddy_uid);
				
				$this->_helper->FlashMessenger($this->translate->_('flash_buddy_deleted'));
			}
		}
		
		$this->_redirect('/profile_' . $user_uid . '.html');
	}
	
	
	
	/*
	 * init the bbcode-editor
	 * 
	 * @param null
	 * 
	 * @return null
	 */
	public function initEditor()
	{
		$baseurl = new MHDEV_View_Helper_BaseUrl();
		#$this->view->headScript()->appendScript('var basePath = \'' . $baseurl->BaseUrl() . '\';');
		$this->view->headScript()->appendFile($baseurl->BaseUrl() . '/static/js/editor.js');
	}
}
?>